package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.repository.ApArticleSearchRepository;
import com.heima.search.service.IApArticleSearchService;
import com.heima.search.service.IApUserSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;

@Service
public class ApArticleSearchServiceImpl implements IApArticleSearchService {

    @Autowired
    private ApArticleSearchRepository repository;

    @Autowired
    private IApUserSearchService userSearchService;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        if (StringUtils.isEmpty(dto.getSearchWords().trim())) {
            return ResponseResult.okResult(new ArrayList<ApArticleSearch>());
        }
        // 根据标题查询分页数据
        // 构建分页条件 指定 当前页  每页条数 排序方向 排序字段
        Pageable page = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.Direction.DESC, "publishTime");
        // 构建查询条件
        QueryBuilder query = QueryBuilders.matchQuery("title", dto.getSearchWords());
        Page<ApArticleSearch> searchPage = repository.search(query, page);

        // 异步保存搜索记录
        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setEquipmentId(dto.getEquipmentId());
        User user = AppThreadLocalUtil.get();
        if (user != null) {
            userSearch.setUserId(user.getUserId());
            userSearch.setEquipmentId(null);
        }
        userSearch.setKeyword(dto.getSearchWords());
        userSearch.setCreatedTime(new Date());
        userSearchService.saveRecord(userSearch);
        return ResponseResult.okResult(searchPage.getContent());
    }
}
